package co.dreamapps.dodoattack.activities;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import co.dreamapps.dodoattack.R;
import co.dreamapps.dodoattack.configuration.Constants;
import co.dreamapps.dodoattack.configuration.Persistence;
import co.dreamapps.dodoattack.social.ConnectionDetector;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;


public class MenuActivity extends Activity implements OnClickListener {

	/**
	 * Twitter keys
	 */
	static String TWITTER_CONSUMER_KEY = "VJzEGcYtaxMRU0944O0VJIdz3"; // place your cosumer key here
	static String TWITTER_CONSUMER_SECRET = "4LIxGrAsyJIJL9gsiUQSHECeL2UkmxCKyYodr2CUJZIoKsophW"; // place your consumer secret here

	/**
	 * Preference Constants	
	 */
	static String PREFERENCE_NAME = "twitter_oauth";
	static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
	static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
	static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

	static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

	/**
	 * Twitter oauth urls
	 */
	static final String URL_TWITTER_AUTH = "auth_url";
	static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
	static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

	/**
	 * Twitter
	 */
	private static Twitter twitter;
	private static RequestToken requestToken;
	private AccessToken accessToken;

	// Shared Preferences
	private static SharedPreferences mSharedPreferences;

	// Internet Connection detector
	private ConnectionDetector cd;

	//Usuario
	private String Username = ""; 

	/**
	 * Configuration
	 */
	private Persistence persistence;

	/**
	 * Visual elements
	 */
	private EditText changeNameEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Oppening configuration
		persistence = new Persistence(this);

		// Configure window
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_menu);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		// Buttons
		ImageButton findChickensInFarmButton = (ImageButton) findViewById(R.id.findChickensInFarmButton);
		findChickensInFarmButton.setOnClickListener(this);
		ImageButton createFarmButton = (ImageButton) findViewById(R.id.createFarmButton);
		createFarmButton.setOnClickListener(this);
		ImageButton btnLoginTwitter = (ImageButton) findViewById(R.id.btnLoginTwitter);
		btnLoginTwitter.setOnClickListener(this);

		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			Log.e("Camilo","Inet down");
			Toast.makeText(getApplicationContext(),
					"No hay una conexion a Internet", Toast.LENGTH_LONG).show();
			return;
		}

		// EditText
		changeNameEditText = (EditText) findViewById(R.id.changeNameEditText);
		changeNameEditText.setOnClickListener(this);
		changeNameEditText.setText(persistence.username);

		// Shared Preferences
		mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

		/** 
		 * Reviso esto una vez me redirija la pagina de Twitter
		 * */
		if (!isTwitterLoggedInAlready()) {
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
				// oAuth verifier
				final String verifier = uri
						.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

				try {

					Thread thread = new Thread(new Runnable(){
						@Override
						public void run() {
							try {

								// Get the access token
								MenuActivity.this.accessToken = twitter.getOAuthAccessToken(
										requestToken, verifier);

							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
					thread.start();
					thread.join();
					// Shared Preferences
					Editor e = mSharedPreferences.edit();

					// After getting access token, access token secret
					// store them in application preferences
					e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(PREF_KEY_OAUTH_SECRET,
							accessToken.getTokenSecret());
					// Store login status - true
					e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
					e.commit(); // save changes


					this.Username = accessToken.getScreenName();
					persistence.username = this.Username;
					changeNameEditText.setText(this.Username);
					Toast.makeText(getApplicationContext(),
							"Bienvenido "+this.Username, Toast.LENGTH_LONG).show();


				} catch (Exception e) {
					// Check log for login errors
					Log.e("Twitter Login Error", "> " + e.getMessage());
					e.printStackTrace();
				}
			}
		}

	}

	@Override
	public void onClick(final View v) {

		switch (v.getId()) {

		case R.id.createFarmButton:

			if(persistence.username.length() == 0) {
				changeName();
			} else {
				startGame();
			}
			break;

		case R.id.findChickensInFarmButton:
			if(persistence.username.length() == 0) {
				changeName();
			} else {
				Intent intent = new Intent(this, MenuScrollerActivity.class);
				intent.putExtra(Constants.MODE, Constants.MODE_ATTACKING);
				startActivity(intent);
			}
			break;

		case R.id.changeNameEditText:
			changeName();
			break;

		case R.id.btnLoginTwitter:
			v.setEnabled(false);
			loginToTwitter();

			Thread thread = new Thread(new Runnable(){
				@Override
				public void run() {
					try {

						Thread.sleep(5000);
						v.setEnabled(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});

			thread.start();
			break;
		}
	}

	public void changeName() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Your name");
		alert.setMessage("Write someting that identifies you in the farm");
		final EditText input = new EditText(this);
		input.setText(changeNameEditText.getText());
		alert.setView(input);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				changeNameEditText.setText(input.getText());
				persistence.username = input.getText().toString();
			}
		});
		alert.show();
	}

	public void startGame() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Starting a new game");
		alert.setMessage("Set a password");
		final EditText input = new EditText(this);
		input.setText(changeNameEditText.getText());
		alert.setView(input);
		alert.setPositiveButton("Start", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				if(input.length() < 3) {
					Toast.makeText(getApplicationContext(), "Password must have at least 3 characters", Toast.LENGTH_SHORT).show();
				} else {
					Intent intent = new Intent(getApplicationContext(), MenuScrollerActivity.class);
					intent.putExtra(Constants.MODE, Constants.MODE_RACING);
					intent.putExtra(Constants.PASSWORD, input.getText().toString());
					startActivity(intent);
				}
			}
		});
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Do nothing
			}
		});
		alert.show();
	}

	@Override
	protected void onPause() {
		persistence.commitChanges();
		super.onPause();
	}

	private boolean isTwitterLoggedInAlready() {
		// return twitter login status from Shared Preferences
		return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
		//	    	return false;
	}

	/**
	 * Function to login twitter
	 * */

	private void loginToTwitter() {
		// Check if already logged in
		if (!isTwitterLoggedInAlready()) {
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
			builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
			Configuration configuration = builder.build();

			TwitterFactory factory = new TwitterFactory(configuration);
			twitter = factory.getInstance();

			Thread thread = new Thread(new Runnable(){
				@Override
				public void run() {
					try {

						requestToken = twitter
								.getOAuthRequestToken(TWITTER_CALLBACK_URL);
						MenuActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
								.parse(requestToken.getAuthenticationURL())));

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			thread.start();         
		} else {
			// user already logged into twitter
			logoutFromTwitter();
		}
	}

	/**
	 * Function to logout from twitter
	 * It will just clear the application shared preferences
	 * */
	private void logoutFromTwitter() {
		// Clear the shared preferences
		Editor e = mSharedPreferences.edit();
		e.remove(PREF_KEY_OAUTH_TOKEN);
		e.remove(PREF_KEY_OAUTH_SECRET);
		e.remove(PREF_KEY_TWITTER_LOGIN);
		e.commit();
	}

}
